<template>
  <div class="hello">
    <h1 @click="flag=false">注册</h1>
    <h1 @click="flag=true">登录</h1>
    <form action="" v-show="!flag">
      姓名：<input type="text" name="username" v-model="userName"><br>
      密码：<input type="password" name="password" v-model="password"><br>
      年龄：<input type="text" name="age" v-model="age"><br>
      电话：<input type="text" name="phonenum" v-model="phonenum"><br>
      <button type="button" @click="addUser">提交信息</button>
    </form>
    <form action="" v-show="flag">
      姓名：<input type="text" name="username" v-model="userName"><br>
      密码：<input type="password" name="password" v-model="password"><br>
      <button type="button" @click="login">登录</button>
    </form>
  </div>
</template>

<script>
  import axios from 'axios'
  export default {
      name: "login",
      data(){
        return{
          flag: true,
          userName:'',
          password:'',
          phonenum:'',
          age: ''
        }
      },
      methods:{
        //登录
        login(){
          let name = this.userName;
          let password = this.password;
          if(password ==''||name ==''){
              alert('密码或者账号不能为空')
            return;
          }
          axios.post('api/user/Userlogin',{name,password}).then(res=>{
            if(res.data.mess != '登录成功'){
              alert(res.data.mess)
              return;
            }
              alert(res.data.mess)
              this.$router.push({
                path: '/homepage'
              }).catch(err=>{
                console.log(err)
              })
          })
        },
        //用户注册
        addUser(){
          let name = this.userName;
          let age = this.age;
          let password = this.password;
          let phonenum = this.phonenum;
          var num = phonenum.length
          //正则判断是否 是存数字
          const result = /^\d+$/.test(phonenum);
          if(num != 11 || !result){
            alert('请输入正确的电话信息');
            return;
          }
          axios.post('/api/user/addUser',{
            name,age,password,phonenum
          }).then( res=>{
            if(res.data.mess != '注册成功' ){
              this.userName = '';
              this.age = '';
              this.password = '';
              this.phonenum = '';
              alert(res.data.mess);
              return;
            }
            alert(res.data.mess)
          }).catch(err=>{
            console.log(err)
          })
        },
      }
    }
</script>

<style scoped>

</style>
